import { type App, h, render } from 'vue'
import { debounce } from 'lodash'

/**
 * backTop
 * @param app
 */
export const scrollElement = (app: App) => {
  const scrollFn = debounce((e) => {
    if (e.target?.scrollTop > 500) {
      ;(document.querySelector('.backtop-container') as any).style.transform =
        'none'
    } else {
      ;(document.querySelector('.backtop-container') as any).style.transform =
        'translateX(200%)'
    }
  }, 100)
  app.directive('scroll', {
    mounted: (el: HTMLElement) => {
      const node = h(
        'div',
        {
          class: 'backtop-container',
          onClick: () => {
            el.scrollTo({
              top: 0,
              behavior: 'smooth' // 平滑效果
            })
          }
        },
        h(
          'svg',
          { class: 'icon font', 'aria-hidden': true },
          h('use', { 'xlink:href': '#icon-fanhuidingbu' })
        )
      )
      render(node, el)
      el.addEventListener('scroll', scrollFn)
    },
    beforeUnmount: (el: HTMLElement) => {
      el.removeEventListener('scroll', scrollFn)
    }
  })
}
